﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.UI;

namespace wpdotnet.Controls
{
    public class WpPosts : WpControl
    {
        protected override void Render(HtmlTextWriter writer)
        {
            writer.Write(GetPosts());
        }

        private string GetPosts()
        {
            StringBuilder menu = new StringBuilder();
            if (string.IsNullOrEmpty(CssClass))
            {
                menu.AppendLine("<div>");
            }
            else
            {
                menu.AppendFormat("<div class=\"{0}\">", CssClass);
                menu.AppendLine();
            }

            List<DAL.PostItem> posts = GetPostsList();
            if (posts != null)
            {
                foreach (DAL.PostItem post in posts)
                {
                    // todo define templates !
                    menu.AppendFormat("<div>{0}<br/>{1}</div>", post.Title, post.Content);
                    menu.AppendLine();
                }
            }
            else
            {
                menu.AppendLine("<div>An error occured while rendering posts.</div>");
            }
            menu.AppendLine("</div>");
            return menu.ToString();
        }


        private List<DAL.PostItem> GetPostsList()
        {
            if (IsCacheEnabled)
            {
                if (CacheManager.Contains(_cacheKey))
                {
                    return CacheManager.Get<List<DAL.PostItem>>(_cacheKey);
                }
            }

            List<DAL.PostItem> posts = WpManager.GetPosts();

            if (posts != null)
            {
                if (IsCacheEnabled)
                {
                    CacheManager.Insert(_cacheKey, posts);
                }
            }

            return posts;

        }
    }
}
